package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 关注用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {

        //1. 校验参数
        if (dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.获取登录人信息
        ApUser apUser = AppThreadLocalUtil.getApUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //游客身份不能进行一下操作
        if (apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH,"游客身份禁止，需进行登入");
        }

        //2.判断用户和作者是否已经相互关注，查询redis
        //2.1 获取关注缓存hash类型的key
        String follow_hash_key="USER_FOLLOW_"+apUser.getId();
        //2.2获取粉丝缓存hash类型的key
        String fans_hash_key="USER_FANS_"+dto.getAuthorId();
        //2.3判断是否相互关注，查询关注缓存中的小key是否包含作者id
        Boolean hasKeyFlag = redisTemplate.opsForHash().hasKey(follow_hash_key, dto.getAuthorId()+"");


        //3.用户未关注
        if(!hasKeyFlag && dto.getOperation()==0){//要执行关注行为操作
            //保存数据到redis中
            redisTemplate.opsForHash().put(follow_hash_key,dto.getAuthorId()+"","1");
            redisTemplate.opsForHash().put(fans_hash_key,apUser.getId()+"","1");
            //保存数据到mongo中
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setUserId(apUser.getId().longValue());
            mongoTemplate.insert(apFollowBehavior);
            return ResponseResult.okResult(3005,"用户关注成功");
        }
        //4.用户已关注
        if(hasKeyFlag && dto.getOperation()==0){//表示已经关注了，无须任何操作
            return ResponseResult.okResult(AppHttpCodeEnum.FOLLOW_USER_SUCCESS);
        }
        if(hasKeyFlag && dto.getOperation()==1){//表示要执行取消关注操作
            //3.1 则删除缓存数据
            redisTemplate.opsForHash().delete(follow_hash_key,dto.getAuthorId()+"");
            redisTemplate.opsForHash().delete(fans_hash_key,apUser.getId()+"");
            //3.2 删除mongodb中的数据
            Query query= Query.query(Criteria.where("userId").is(apUser.getId())
                    .and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query,ApFollowBehavior.class);
            return ResponseResult.okResult(3004,"删除成功");
        }
        return null;
    }
}
